/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.niedziela12.pai.ejb.user.facades;

import com.niedziela12.pai.ejb.AbstractFacade;
import com.niedziela12.pai.ejb.entities.Role;
import com.niedziela12.pai.ejb.entities.User;
import com.niedziela12.pai.ejb.entities.UserRoles;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Kamil
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public class UserFacade extends AbstractFacade<User> implements UserFacadeLocal {
    @PersistenceContext(unitName = "com.niedziela12.pai.ejb")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UserFacade() {
        super(User.class);
    }

    @Override
    public User findUserByLogin(String login) {
        return (User) em.createNamedQuery("User.userByLogin").setParameter("login", login).getSingleResult();
    }
    
    @Override
    public List<UserRoles> getUsersRoles(User user) {
        return (List<UserRoles>) em.createQuery("SELECT r FROM User u INNER JOIN u.userRolesList r WHERE u.id = :idLogin")
                .setParameter("idLogin", user.getId()).getResultList();
    }
     
    @Override
    public void editRoles(List<UserRoles> roles) {
        for (UserRoles userRoles : roles) {
            em.merge(userRoles);
        }
    }
    
    @Override
    public List<Role> findRolesDef() {
        return (List<Role>) em.createQuery("SELECT r FROM Role r").getResultList();
    }
}
